import tkinter as tk
from tkinter import filedialog
import inspect
import sys
import importlib
from tkinter import BooleanVar


class FileSelectFrame(tk.Frame):
    def __init__(self, master, args_dict:dict, bool:BooleanVar, **kwargs):
        super().__init__(master, highlightbackground="grey", highlightthickness=2, **kwargs)
        self.args_dict = args_dict
        self.args_bool = bool

        self.fileLabel = tk.Label(self, text="文件路径：")
        self.fileEntry = tk.Entry(self)  # 这是输入框
        self.fileBtn = tk.Button(self, text="查询", height=1, command=self.btn_event)
        self.fileLabel.pack(side='left')
        self.fileEntry.pack(side='left',padx=5, expand=True, fill='x')
        self.fileBtn.pack(side='left')
        self.pack(padx=5,pady=10,ipadx=5,ipady=5, fill='x')

    def btn_event(self):  # 这是获取路径函数
        self.fileEntry.delete(0, "end")
        path = filedialog.askopenfilename()
        # path = filedialog.askdirectory()
        path = path.replace("/", "\\")  # 通过replace函数替换绝对文件地址中的/来使文件可被程序读取 #注意：\\转义后为\，所以\\\\转义后为\\
        self.fileEntry.insert('insert', path)

        dir_path: str = '\\'.join(path.split('\\')[:-1])
        module_name: str = path.split('\\')[-1].split('.')[0]
        sys.path.append(dir_path)
        print(dir_path)
        # 动态导入——————很关键
        my_module = importlib.import_module(module_name)
        print(my_module.ajy_run_case(1,2))
        argspec = inspect.getfullargspec(my_module.ajy_run_case)
        for i in range(len(argspec.args)):
            key = argspec.args[i]
            value = argspec.defaults[i]
            self.args_dict[key] = value
        print(self.args_dict)
        self.args_bool.set(True)

if __name__ == '__main__':
    d:dict = {}
    window = tk.Tk()
    boolVar = BooleanVar()
    window.title("亲情导出————模块的动态导入")
    window.geometry('400x300')
    fileWindow = FileSelectFrame(window, d, boolVar)

    window.mainloop()